package com.song.service.login;

import com.song.dao.user.UserDao;
import com.song.entity.Constants;
import com.song.entity.user.User;
import com.song.enums.UserStatusEnum;
import com.song.exception.user.UserBlockedException;
import com.song.exception.user.UserDeleteException;
import com.song.exception.user.UserNotExistsException;
import com.song.exception.user.UserPasswordNotMatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserDao userDao;

    @Override
    public User login(String account, String password) {

        // 用户名 或者 密码为空
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            throw new UserNotExistsException();
        }
        // 密码最大长度
        if (password.length() < Constants.PASSWORD_MIN_LENGTH
                || password.length() > Constants.PASSWORD_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }
        // 用户名长度限制
        if (account.length() < Constants.USERNAME_MIN_LENGTH
                || account.length() > Constants.USERNAME_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }

        User user = userDao.selectUserByAccount(account);
        if (user == null) {
            throw new UserNotExistsException();
        }

        // 判断用户状态
        if (UserStatusEnum.DELETED.getCode() == user.getStatus()) {
            throw new UserDeleteException();
        }

        if (UserStatusEnum.DISABLE.getCode() == user.getStatus()) {
            throw new UserBlockedException();
        }

        // 限制登录次数

        // 校验密码
        if (!password.equals(user.getPassword())) {
            throw new UserPasswordNotMatchException();
        }
        return user;
    }
}
